import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../common/guard/auth.service';
import {WebsocketService} from '../../common/http-interceptors/websocket.service';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
    selector: 'app-web-socket',
    templateUrl: './web-socket.component.html',
    styleUrls: ['./web-socket.component.less']
})
export class WebSocketComponent implements OnInit {
    msg  = ''
    msgList: any[] = [];
    user = {
        username: this.authService.getToken(),
        headPortrait: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'
    };

    constructor(
        private authService: AuthService,
        private websocketService: WebsocketService,
        private message: NzMessageService,
    ) {}

    handleSubmit(): void {
        const msg = this.msg;
        this.websocketService.sendMessage({...this.user, msg});
        this.msg = ''
    }
    toJson(str) {
        return (new Function('return ' + str))();
    }
    toDate(str) {
        return  Date.parse(str);
    }
    initSocket() {
        this.websocketService.createObservableSocket('ws://localhost:9010/webSocket/' + this.authService.getToken()).subscribe(data => {
                this.msgList = [...this.msgList, {...this.toJson(data)}];
            },
            err => this.message.info(err),
            () =>  this.message.info('流已经结束') //  最后结束后，会执行到这的
        );
    }


    ngOnInit(): void {
        this.initSocket();
    }
}
